//
//  ConfigServerVC.m
//  QGSPos
//
//  Created by vinh pham on 5/29/13.
//  Copyright (c) 2013 QGS Inc. All rights reserved.
//

#import "ConfigServerVC.h"
#import "ListServerVCNew.h"

@interface ConfigServerVC ()

@end

@implementation ConfigServerVC
@synthesize parent;
@synthesize inforDict;
@synthesize isEdit;
@synthesize isOnlineServer;
@synthesize txtServerLink;
@synthesize txtUsername,txtPassword;
@synthesize containerView;
@synthesize mainSwitch;
@synthesize lbAuthenticate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        parent = _parent;
        
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
    }
    return self;
}

- (IBAction) switchAuthenticate:(id)sender {
    containerView.hidden = !mainSwitch.on;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"Input Server";
    UIBarButtonItem *btnDone = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(done)];
    self.navigationItem.rightBarButtonItem = btnDone;
    
    if (isEdit) {
        txtServerLink.text = [inforDict objectForKey:@"serverLink"];
        if (!isOnlineServer) {
            txtUsername.text = [inforDict objectForKey:@"username"];
            txtPassword.text = [inforDict objectForKey:@"password"];
            mainSwitch.on = [[inforDict objectForKey:@"isAuthentication"] boolValue];
            containerView.hidden = !mainSwitch.on;
        }
        else {
            lbAuthenticate.hidden = mainSwitch.hidden = containerView.hidden = YES;
        }
    }
    else {
        txtServerLink.text = @"";
        txtUsername.text = @"";
        txtPassword.text = @"";
        if (!isOnlineServer)
            mainSwitch.on = NO;
        else {
            mainSwitch.hidden = YES;
            lbAuthenticate.hidden = YES;
        }
        containerView.hidden = YES;
    }
    [self setContentSizeForViewInPopover:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];
}

- (void) done {
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if ([txtServerLink.text isEqualToString:@""]) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.config-server.inputURL"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    NSRange R1 = [txtServerLink.text rangeOfString:@"http://" options:NSCaseInsensitiveSearch];
    NSRange R2 = [txtServerLink.text rangeOfString:@"https://" options:NSCaseInsensitiveSearch];
    if (R1.location != NSNotFound || R2.location != NSNotFound) {
        //ok
    }
    else {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"lgeneral.warning"] message:[dictLanguage objectForKey:@"login.config-server.wrongURL-message"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    if (!isOnlineServer) {
        if (mainSwitch.on) {
            if ([txtUsername.text isEqualToString:@""]){
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.config-server.input-user-name"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
            if ([txtPassword.text isEqualToString:@""]){
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.config-server.input-password"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
        }
        NSString * strTemp = [txtServerLink.text substringFromIndex:7];
        NSArray * array = [strTemp componentsSeparatedByString:@"/"];
        
        if (!isEdit) { // is add new
            if ([array count] >= 2) {
                if ([self checkDuplicateServer:[(ListServerVCNew*)parent arrayServer]]){
                    UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.config-server.URL-existed"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                    [dialog show];
                    return;
                }
            }
            NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
            if (array && [array count] > 1) {
                dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:txtServerLink.text,@"serverLink",[NSNumber numberWithBool:NO],@"isCheck",txtUsername.text,@"username",txtPassword.text,@"password",[NSNumber numberWithBool:mainSwitch.on],@"isAuthentication", nil];
                
            }
            else
            {
                NSString * serverLink = [NSString stringWithFormat:@"%@/%@",txtServerLink.text,[userDefaults objectForKey:CURRENT_USER_NAME_URL]];
                //NSLog(@"%@",[userDefaults objectForKey:SERVER_ACCOUNT_ID]);
                 dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:serverLink,@"serverLink",[NSNumber numberWithBool:NO],@"isCheck",[userDefaults objectForKey:CURRENT_USER_NAME_URL],@"username",[userDefaults objectForKey:CURRENT_USER_PASS_URL],@"password",[NSNumber numberWithBool:YES],@"isAuthentication", nil];
            }
            [[(ListServerVCNew*)parent arrayOfflineServer] addObject:dict];
        }
        else {
            
            [inforDict setObject:txtServerLink.text forKey:@"serverLink"];
            [inforDict setObject:txtUsername.text forKey:@"username"];
            [inforDict setObject:txtPassword.text forKey:@"password"];
            [inforDict setObject:[NSNumber numberWithBool:mainSwitch.on] forKey:@"isAuthentication"];
        }
        [userDefaults setObject:[(ListServerVCNew*)parent arrayOfflineServer] forKey:OFFLINE_SERVER_ARRAY];
    }
    else {
        if (!isEdit) {
            if ([self checkDuplicateServer:[(ListServerVCNew*)parent arrayServer]]){
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.config-server.URL-existed"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }

            NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:txtServerLink.text,@"serverLink",[NSNumber numberWithBool:NO],@"isCheck",[NSNumber numberWithBool:YES],@"canEdit", nil];
            [[(ListServerVCNew*)parent arrayServer] addObject:dict];
        }
        else {
            if ([self checkDuplicateServer:[(ListServerVCNew*)parent arrayServer]]){
                UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.config-server.URL-existed"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
                [dialog show];
                return;
            }
            else {
                [inforDict setObject:txtServerLink.text forKey:@"serverLink"];
            }
        }
        [userDefaults setObject:[(ListServerVCNew*)parent arrayServer] forKey:ONLINE_SERVER_ARRAY];
    }
    [[(ListServerVCNew*)parent mainTableView] reloadData];
    [self.navigationController popViewControllerAnimated:YES];
}

- (BOOL) checkDuplicateServer:(NSMutableArray*)_serverArray {
    BOOL isDuplicate = NO;
    for (int i=0;i < [_serverArray count];i++) {
        NSMutableDictionary *dict = [_serverArray objectAtIndex:i];
        NSString *serverLink = [dict objectForKey:@"serverLink"];
        //kiem tra neu khong trung` voi list server hien tai hoac edit chinh no.
        if ([txtServerLink.text isEqualToString:serverLink] && ![serverLink isEqualToString:[inforDict objectForKey:@"serverLink"]]) {
            isDuplicate = YES;
            break;
        }
    }
    return isDuplicate;
}

@end
